package com.bby.screentool;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bby.screentool.base.RuntimeEnv;
import com.bby.screentool.databinding.ActivityMainBinding;
import com.bby.screentool.manager.WebRtcResourceManager;
import com.bby.screentool.utils.CacheUtils;
import com.bby.screentool.utils.ScreenUtils;
import com.bby.screentool.vm.ScreenRecorderViewModel;

import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer;

import java.util.Optional;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "====================>";
    private static final int RECORD_REQUEST_CODE = 101;
    private static final int PERMISSION_REQUEST_CODE = 1101;

    private ActivityMainBinding binding;
    private ScreenRecorderViewModel viewModel;
    private ActivityResultLauncher<Intent> launcher;
    private SurfaceViewRenderer localSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 判断结果是否是成功的
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        viewModel.setProjectionResultData(data);
                    }
                });
        checkPermission();
        RuntimeEnv.setUserId(CacheUtils.getUserId(this));
        RuntimeEnv.DEFAULT_WIDTH = RuntimeEnv.RECORD_WIDTH = Math.min(ScreenUtils.getScreenWidth(this), 720);
        RuntimeEnv.DEFAULT_HEIGHT = RuntimeEnv.RECORD_HEIGHT = Math.min(ScreenUtils.getScreenHeight(this), 1280);
        initViewModel();
        localSurfaceView=findViewById(R.id.localSurfaceView);
        localSurfaceView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        localSurfaceView.init(WebRtcResourceManager.eglBase.getEglBaseContext(), new RendererCommon.RendererEvents() {
            @Override
            public void onFirstFrameRendered() {
            }

            @Override
            public void onFrameResolutionChanged(int videoWidth, int videoHeight, int rotation) {
            }
        });
    }

    private void initViewModel() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(ScreenRecorderViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        viewModel.getToast().observe(this,this::makeToast);
        viewModel.getEvent().observe(this,event->{
            switch (event){
                case ASK_PROJECTION:
                    askProjection();
                    break;
                case START_LOCAL_VIEW:
                    localSurfaceView.setVisibility(View.VISIBLE);
                    Optional.ofNullable(WebRtcResourceManager.getInstance().getVideoTrack())
                            .ifPresent(videoTrack -> videoTrack.addSink(localSurfaceView));
                    break;
                case STOP_LOCAL_VIEW:
                    localSurfaceView.setVisibility(View.INVISIBLE);
                    Optional.ofNullable(WebRtcResourceManager.getInstance().getVideoTrack())
                            .ifPresent(videoTrack -> videoTrack.removeSink(localSurfaceView));
                    break;
            }
        });
    }

    private void checkPermission() {
        String[] pms = new String[]{Manifest.permission.RECORD_AUDIO};
        if (hasPermissions(pms)) {
            Log.d(TAG, "checkMyPermission: 有权限");
            askProjection();
        } else {
            ActivityCompat.requestPermissions(this, pms, PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 判断请求码是否匹配
        if (requestCode == PERMISSION_REQUEST_CODE) {
            // 判断是否所有的权限都被授予了
            if (hasPermissions(permissions)) {
                // 如果都被授予了，再请求录屏
                askProjection();
            } else {
                // 如果有任何一个权限被拒绝了，init示用户需要授予所有的权限才能使用功能，并关闭当前Activity
                Toast.makeText(this, "You need to grant all the permissions to use this feature", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void askProjection() {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        launcher.launch(captureIntent);
    }

    private boolean hasPermissions(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void makeToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
    }

}